// singleton.js
const { BrowserWindow } = require("electron");
const { default: WinState } = require("electron-win-state");
const path = require("path");

let instance = null;

const init = () => {
  // 单例的初始化逻辑
  const winState = new WinState({
    defaultHeight: 1000,
    defaultWidth: 800,
    // 防止窗口共享状态
    electronStoreOptions:{
        name:'window-state-main'
    }
  });
  const win = new BrowserWindow({
    // 自定义窗口的状态
    ...winState.winOptions,
    show:false,
    // fullscreen:true,

    webPreferences: {
      // 预加载的js
      preload: path.resolve(__dirname, "../preload/index.js"),
    },
  });
  win.maximize()
  win.loadURL("http://localhost:3001/");
  // win.loadURL("http://baidu.com/");
  win.webContents.openDevTools();
  winState.manage(win);
  win.on('ready-to-show',()=>{
    win.show();
  })

  // 配置CSP规则
  const session = win.webContents.session;
  session.webRequest.onHeadersReceived((details, cb) => {
    cb({
      responseHeaders: {
        ...details.responseHeaders,
        "Content-Security-Policy": [
            "default-src * 'unsafe-inline'; \
            img-src * data:;\
            style-src * 'unsafe-inline';\
            font-src *;\
            script-src * 'unsafe-inline' 'unsafe-eval'",
          ],
      },
    });
  });
  
  return win
};

const getInstance = () => {
  if (!instance) {
    instance = init();
  }
  return instance;
};
MainWindow = {
    getInstance
};

module.exports = {
    MainWindow
}
